/*
 * Author Niharika Soni
 */
package com.NewsFeedClasses;


import java.util.ArrayList;
import com.restfb.Connection;
import com.restfb.FacebookClient;
import com.restfb.types.Post;


//NewsFeedPosts class responsible fetching news feeds from facebook
public class NewsFeedPosts {
	private FacebookClient facebookClient;
	private Connection<Post> newsFeedConnection; // Connection of type Post to fetch News feeds
	
	//constructor to initialize NewsFeedPosts class
	//FacebookClient as input parameter
	public NewsFeedPosts(FacebookClient facebookClient)
	{
		this.facebookClient = facebookClient;
		//connection String "me/home" to fetch the news feed data from user home page
		//Post.class Connection type to fetch the news feed posts
		this.newsFeedConnection = facebookClient.fetchConnection("me/home", Post.class);
	}
	
	public ArrayList<NewsFeed> fetchNewsFeedPosts()
	{
		ArrayList<NewsFeed> newsFeedList = new ArrayList<NewsFeed>(); //list to add NewsFeed objects
		int feedCount = 0;
	  	NewsFeed newsFeedObject;
		int countPageSize = newsFeedConnection.getData().size(); // number of newsfeeds in a page
	    do
	    {
	    	newsFeedObject = new NewsFeed();
	    	//populating news feed object's state
	    	newsFeedObject.setNewsFeedType(this.newsFeedConnection.getData().get(feedCount).getType());
	    	newsFeedObject.setNewsFeedID(this.newsFeedConnection.getData().get(feedCount).getId());
	    	newsFeedObject.setNewFeedLikeCount(this.newsFeedConnection.getData().get(feedCount).getLikesCount());
	    	newsFeedObject.setNewsFeedName(this.newsFeedConnection.getData().get(feedCount).getName());
	    	newsFeedObject.setNewsFeedLink(this.newsFeedConnection.getData().get(feedCount).getLink());
	    	newsFeedObject.setNewsFeedMessage(this.newsFeedConnection.getData().get(feedCount).getMessage());
	    	// adding news feeds to arraylist
	    	newsFeedList.add(newsFeedObject);
	    	feedCount++;
	    	if(feedCount == countPageSize)
	    	{
	    		newsFeedConnection = facebookClient.fetchConnectionPage(newsFeedConnection.getNextPageUrl(), Post.class);
	    		countPageSize = newsFeedConnection.getData().size();
	    		feedCount = 0;
	    	}
	    	
	    }while(newsFeedConnection.hasNext());
	    
	    return newsFeedList;
	}
	
}
 